package project.messagestack.network.facebook;


import java.util.List;

import project.messagestack.R;
import project.messagestack.utils.DatabaseManager;
//import project.messagestack.utils.Logger;
//import com.easy.facebook.android.apicall.FQL;
import com.easy.facebook.android.apicall.GraphApi;
import com.easy.facebook.android.data.Comment;
//import com.easy.facebook.android.data.JSONSingleObjectDecode;
import com.easy.facebook.android.data.Message;
import com.easy.facebook.android.data.User;
import com.easy.facebook.android.error.EasyFacebookError;
import com.easy.facebook.android.facebook.FBLoginManager;
import com.easy.facebook.android.facebook.Facebook;
import com.easy.facebook.android.facebook.LoginListener;
import android.app.Activity;
//import android.content.Intent;
import android.os.Bundle;

/** Klasa odpowiedzialna za obsługę wiadomości facebook'a.
*
*  Odpowiada za: logowanie do konta na fecebook'u, pobranie wiadomości,
*  przeparsowanie ich do odpowiedniego formatu oraz przekazanie do klasy
*  {@link project.messagestack.utils.DatabaseManager DatabaseManager}.
*  
*  @see FacebookConnect#onCreate
*  @see FacebookConnect#shareFacebook
*  @see FacebookConnect#onLoginFail
*  @see FacebookConnect#onLoginSuccess
*  @see project.messagestack.message_stack
*/
public class FacebookConnect extends Activity   implements LoginListener {

	private FBLoginManager fbManager;
	private User mMe;
	private GraphApi ga;
	private DatabaseManager dm;
	private List<Message> msg;
	private project.messagestack.network.mail.Message message;
	//Intent intentResult;

	
	@Override
	/** Funkcja uruchamiana podczas startu activity FacebookConnect. Wywołuje metodę 
	 * {@link project.messagestack.network.facebook#shareFacebook() shareFacebook()}.
	 *
	 *  @param savedInstanceState Jeśli activity jest reinicjalizowane po uprzednim zamknięciu, wtedy to Bundle zawiera dane z poprzedniej sesji.
	 */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//intentResult=new Intent(getApplicationContext(),IntentResult.class);
		shareFacebook();
		
	}
	
	/** Funkcja odpowiedzialna za zalogowanie się do konta na Facebook'u. */
	public void shareFacebook() {
		/** Zmienna finalna przechowująca zezwolenia do konta na Facebook'u. */
		String permissions[] = {"email","read_stream","read_requests","read_mailbox","offline_access"};
		
		fbManager = new FBLoginManager(this, "Message-stack",
                "1530d5650e04c870a646993309a84639","fac99940f12fe2f1f25d072a25c55aea",
                "196013840442598","http://www.easyfacebookandroidsdk.com/accesstokenpage/",permissions);
		
		if (fbManager.existsSavedFacebook()) {
			fbManager.loadFacebook(R.layout.black);
		} else {
			
			fbManager.login(R.layout.black);
		}
	}

	/** Funkcja wywoływana podczas nieudanego logowania do konta na Facebook'u. */
	public void onLoginFail() {
		fbManager.displayToast("Login failed!");
	}

	private String buildMsg(Message msg) {
	  if (msg.getFrom().getId().equals(mMe.getId()))
	    return null;
	  String result = "", tmp = "";
	  result = "From: ";
    result += msg.getFrom().getName()+"\n";
    result += "Date: ";
    tmp = msg.getUpdated_time();
    tmp = tmp.substring(0, 10)+"-"+tmp.substring(11, 13)+"-"+
      tmp.substring(14, 16)+"-"+tmp.substring(17, 19);
    result += tmp+"\n";
    result += "Subject: ";
    result += msg.getSubject()+"\n";
    result += "Flag: UNSEEN";
    result += "\n\n";
    result += msg.getMessage();
	  return result;
	}
	
	private String buildMsg(Comment msg) {
    if (msg.getFrom().getId().equals(mMe.getId()))
      return null;
    String result = "", tmp = "";
    result = "From: ";
    result += msg.getFrom().getName()+"\n";
    result += "Date: ";
    tmp = msg.getCreated_time();
    tmp = tmp.substring(0, 10)+"-"+tmp.substring(11, 13)+"-"+
      tmp.substring(14, 16)+"-"+tmp.substring(17, 19);
    result += tmp+"\n";
    result += "Subject: \n";
    result += "Flag: UNSEEN";
    result += "\n\n";
    result += msg.getMessage();
    return result;
  }
	
	/** Funkcja wywoływana po udanym logowaniu do konta na Facebook'u. 
	 * 
	 * @param facebook zmienna zawierająca informacje o koncie do którego się zalogowaliśmy
	 */
	public void onLoginSuccess(Facebook facebook) {
		
		ga = new GraphApi(facebook);
		dm = new DatabaseManager(getApplicationContext());
		dm.clearAll();
		try {
		  mMe = ga.getMyAccountInfo();
		  msg = ga.getAllInBoxMy();
			for(int i=0; i<msg.size(); i++) {
			  String s;
			  if ((s = buildMsg(msg.get(i))) != null) {
			    message = new project.messagestack.network.mail.Message(s,
	            project.messagestack.network.mail.Message.msgType.FACEBOOK);
	        dm.addNewMessage(message);
			  }
				for (int j = 0; j < msg.get(i).getComment().size(); j++) {
				  if ((s = buildMsg(msg.get(i).getComment().get(j))) != null) {
				    message = new project.messagestack.network.mail.Message(s,
	              project.messagestack.network.mail.Message.msgType.FACEBOOK);
	          dm.addNewMessage(message);
				  }
				}
				
			}
			//String pkg=getPackageName(); 
			//intentResult.putExtra(pkg+".fql",wynik);
			
		} catch (EasyFacebookError e) {
			e.printStackTrace();
		}
		dm.close();
		//JSONSingleObjectDecode objectjson = new JSONSingleObjectDecode();
		
		//fbManager.logout();
		finish();
    	//startActivity(intentResult);
		


	}
}
